/**
 * 
 */
package com.googlecode.pcapj;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import org.bridj.Pointer;

import com.googlecode.pcapj.bridj.pcap_pkthdr;
import com.googlecode.pcapj.bridj.timeval;

/**
 * 
 */
class CapturedFactory{
	private Map<Integer, DataLinkLayer<? extends Packet>> detaLinkLayers = new LinkedHashMap<Integer, DataLinkLayer<? extends Packet>>();  
	
	Map<Integer, DataLinkLayer<? extends Packet>> getDetaLinkLayers() {
		return detaLinkLayers;
	}

	Packet newPacket(int dataLinkLayerType, byte[] buffer, int offset, int length) {
		PacketFactory<? extends Packet> packetFactory = detaLinkLayers.get(dataLinkLayerType);
		if(packetFactory == null){
			packetFactory = PacketFactoryImpl.DEFAULT_FACTORY;
		}
		return packetFactory.newPacket(buffer, offset, length);
	}
	Captured newCaptured(int dataLinkLayerType, Pointer<pcap_pkthdr> header, Pointer<Byte> pkt_data) throws IOException{
		pcap_pkthdr pkthdr = header.get();
		
		timeval timeval = pkthdr.ts();
		TimeStamp timeStamp = new TimeStamp(timeval.tv_sec(), timeval.suseconds_t());
		int caputuredLength = pkthdr.caplen();
		int length = pkthdr.len();
		
		byte[] packetData = pkt_data.getBytes(length);
		
		Packet packet = newPacket(dataLinkLayerType, packetData, 0, packetData.length);
		
		CapturedImpl captured = new CapturedImpl();
		captured.setTimeStamp(timeStamp);
		captured.setCaputuredLength(caputuredLength);
		captured.setLength(length);
		captured.setPacket(packet);
		
		return captured;
	}
}
